﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Graph;

namespace Crawler
{
    public class HtmlDoc : IHtmlDoc, IComparable<IHtmlDoc>, IEquatable<IHtmlDoc>
    {
        IHTTP iHttp = new HTTP();

        public string Document { get; set; }

        /// <summary>
        /// constructor which takes an url as a parameter
        /// </summary>
        /// <returns></returns>
        public string Title { get; set; }
        public string URL { get; set; }
        public bool Visited { get; set; }
        public IHtmlDoc ParentDoc { get; set; }

        public HtmlDoc(string url)
        {
            URL = url;
            ParentDoc = null;
        }

        public void SetName()
        {
            if (Document != null)
                Title = Regex.Match(Document, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
        }


        public List<IHtmlDoc> GetAllLinks()
        {
            // Download Source & Set Name:
            Document = iHttp.GetSourceCode(URL);
            SetName();

            List<IHtmlDoc> listOfLinks = new List<IHtmlDoc>();

            if (Document != null)
            {
                MatchCollection foundMatches = Regex.Matches(Document, @"(<a\s.*?>.*?</a>)", RegexOptions.Singleline);

                foreach (Match m in foundMatches)
                {
                    string value = m.Groups[1].Value;

                    Match m2 = Regex.Match(value, @"href=\""(.*?)\""", RegexOptions.Singleline);
                    if (m2.Success)
                    {
                        value = m2.Groups[1].Value;
                    }
                    string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                    RegexOptions.Singleline);
                    if (!t.Contains("javascript:") & !t.Contains("mailto:"))
                    {
                        if (t.EndsWith("#"))
                        {
                            t = t.TrimEnd(new char[] { '#' });
                        }
                        Uri basePath = new Uri(URL);
                        Uri newPath = new Uri(basePath, t);
                        listOfLinks.Add(new HtmlDoc(newPath.AbsoluteUri));
                    }
                }
                return listOfLinks;
            }
            else
            {
                return listOfLinks;
            }
        }

        public int CompareTo(IHtmlDoc other)
        {
            return URL.CompareTo(other.URL);
        }

        public bool Equals(IHtmlDoc other)
        {
            return URL.Equals(other.URL);
        }

        public override string ToString()
        {
            return URL;
        }
    }
}
